<?php
/*
 * 订单
 */
namespace app\home\controller;

use app\common\controller\IndexBase;
use think\facade\Session;
use think\facade\Db;
use kuaidi100\Kuaidi; //快递API
use EasyWeChat\Factory; //微信API
use app\common\model\System;

class Orders extends IndexBase
{
    protected function initialize()
    {
        parent::initialize();
        // $options = System::get_config_by_code('wechat');
        $options = [
            // 必要配置
            'app_id'             => 'wxb0521c578e8a9e2e',
            'mch_id'             => '1249391601',
            'key'                => 'KJGllsswlje21o123u8KH8u838odlh8d',   // API 密钥

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
            'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！

            'notify_url'         => '默认的订单回调地址',     // 你也可以在下单时单独设置来想覆盖它
        ];
        $this->app = Factory::payment($options);
    }

    //首页
    public function index()
    {
    	$uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@login'));
    	$data = Db::table('orders')
                ->alias('o')
                ->leftJoin('order_goods g','g.order_id = o.id')
                ->leftJoin('user u','o.user_id = u.id')
                ->field('o.id,u.name user_name,o.order_sn,o.order_status,o.shipping_status,o.pay_status,g.goods_name,g.goods_price,g.goods_attr,g.goods_number,o.shipping_status,o.pay_status,o.consignee,o.city,o.address,o.mobile,o.postscript,o.order_amount,o.money_paid,o.integral,o.balance,o.pay_name,o.pay_time,o.is_separate,o.status')
                ->where('o.user_id',$uid)
                ->order('pay_time','DESC')->paginate();
        return $this->fetch('',['data'=>$data]);
    }

    //详情
    public function order_detail()
    {
    	$uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@login'));
    	$id = md6(input('code'),true);
    	$data = Db::table('orders')
            ->alias('o')
            ->leftJoin('order_goods g','g.order_id = o.id')
            ->leftJoin('user u','o.user_id = u.id')
            ->field('o.id,u.name user_name,o.order_sn,o.order_status,g.goods_name,g.goods_price,g.goods_attr,g.goods_number,o.shipping_status,o.pay_status,o.consignee,o.city,o.address,o.mobile,o.postscript,o.order_amount,o.money_paid,o.integral,o.balance,o.pay_name,o.pay_time,o.is_separate,o.status,o.create_time')->where('o.id',$id)->find();
        return $this->fetch('detail',['data'=>$data]);
    }

    //物流查询
    public function express()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@login'));
        $id = md6(input('code'),true);
        $num = Db::table('orders')->where('id',$id)->value('invoice_no');
        $data = Kuaidi::synquery($num);//物流查询
        return $this->fetch('express',['data'=>$data]);
    }

    //订单支付
    public function pay_order()
    {
        $uid = $this->hashids->decode(UserId());
        !$uid && $this->redirect(url('@login'));
        // if ($this->request->isPost())
        // {
            // $id = md6(input('code'),true);
            $order = Db::table('orders')->alias('o')->leftJoin('order_goods g','g.order_id = o.id')->field('o.id,o.order_sn,o.order_status,g.goods_name,g.img,g.goods_price,g.goods_attr,g.goods_number,o.shipping_status,o.pay_status,o.consignee,o.city,o.address,o.mobile,o.postscript,o.order_amount,o.money_paid,o.integral,o.balance,o.pay_name,o.pay_time,o.is_separate,o.status,o.create_time')->where('o.id',1)->find();
            // $order['pay_status'] === 1 && $this->error('订单已支付！');
            $openid = Db::table('wechat')->where('user_id',$uid)->value('openid');
            dump($openid);
            halt($order);
            $data = [
                'body' => '腾讯充值中心-QQ会员充值',
                'out_trade_no' => build_order_no(),
                'total_fee' => 9998,
                'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $openid
            ];
            $result = $this->app->order->unify($data);
            halt($result['return_msg']);
            $result['return_code'] == 'FAIL' && $this->error($result['return_msg']);
            $this->success('支付成功');
        // }
        // $data = [];
        // return $this->fetch('pay',['data'=>$data]);
    }

    /*
     * 订单支付回调
     *
     */
    public function order_pay_notify_url()
    {
        if ($this->request->isPost())
        {
            $order_sn = $this->request->param('id');
            $order = Db::table('orders')->where(['order_sn'=>$order_sn])->find();
            empty($order) && $this->error('订单不存在！');
            //修改订单支付状态
            $data = [
                'pay_num' =>'', //支付流水号
                'pay_time' =>time(), //支付时间
                'transaction_id' =>'', //微信支付订单号
                'trade_state' =>'' //交易状态
            ];
            Db::table('orders')->where('id',$order['id'])->update($data);
        }
        $this->error('页面被火星人抓走了～');
    }
    /*
     * 订单确认收货
     * @param int $order 订单ID
     * @return boolean
     */
    public function confirm_receipt()
    {
        if ($this->request->isPost())
        {
            $order_sn = $this->request->param('id');
            $order = Db::table('orders')->where(['order_sn'=>$order_sn])->find();
            empty($order) && $this->error('订单已完成！');
            //发放佣金
            return $this->give_commission($order['id']);//根据订单ID发放佣金
        }
        $this->error('页面被火星人抓走了～');
    }

    /*
     * 佣金发放(私有方法)--确认收货或支付成功时调用
     * @param int $order 订单ID
     * @return boolean
     */
    private function give_commission($order_id)
    {
        $order = Db::table('orders')->where('id',$order_id)->find();
        $order['is_separate'] && $this->error('订单已分成！');
        $split_money = 139.9;//abs($order['split_money']); //分成总金额
        $user = Db::table('user')->find($order['user_id']);
        $genes = explode(',',$user['genes']);
        foreach ($genes as $key => $v) {
            if ($v) {
                if ($key ==0) {
                    $percen = 0.5; //分成百分比
                }elseif ($key ==1) {
                    $percen = 0.3; //分成百分比
                }elseif ($key == 2) {
                    $percen = 0.2; //分成百分比
                }else{
                    $percen = 0; //分成百分比
                }
                $setmoney = round($split_money * $percen, 2);//实际分成金额
                if ($setmoney) {
                    echo 1+$key.'层会员ID：'.$v.'==分成金额：'.$setmoney.'==分成比例：'.$percen.'% <br />';
                }
            }
        }
    }

}